<template>
  <div>
    <Modal
      v-model="visible"
      :title="addModelData.title"
      class-name="centerModel"
      @on-cancel="cancel"
      okText="确定"
      width="334"
    > 
      <div class="fromBody">
        <Form :model="form" >
          <FormItem>
            <div style="display:flex;align-items: center;justify-content: space-between;">
              <Select class="formInput" :class="[addModelData.kind>2?'w45':'']" v-model="form.time_point" placeholder="请选择时间段">
                <Option v-for="item in time_point_list" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
              <Input type="number" v-if="addModelData.kind>2" style="width:52%" v-model="form.time_interval" placeholder="请输入相隔时间">
                <span slot="append">分钟</span>
              </Input>
            </div>
          </FormItem>
          <FormItem>
            <Select
              :placeholder="selectPlaceholder"
              v-model="queryId"
              filterable
              clearable
              :remote-method="search"
              :loading="loading">
              <Option v-for="(option, index) in options" :value="option.id" :key="index">{{option.title}}</Option>
            </Select>
          </FormItem>
          <div class="details">
            <div class="item" v-for="(item,index) in details" :key="index">
              <div class="name">{{item.title}}</div>
              <div class="ipArea">
                <Input v-model="item.num" size="small" style="width: 100px">
                  <Select v-model="item.unit_id" slot="append" style="width: 50px;padding:0;">
                      <Option v-for="(item,index) in item.unit_list" :key="index" :value="item.id">{{item.title}}</Option>
                  </Select>
                </Input>
                <Icon class="icon" type="ios-trash" @click="itemDelete(index)" />
              </div>
            </div>
          </div>
          <div class="history">
            <div class="title">历史记录</div>
            <div class="list">
              <div class="item" v-for="(item,index) in historyList" :key="index" @click="addByHistory(item)"><p>{{item.title}}</p></div>
            </div>
          </div>
        </Form>
      </div>
      <div slot="footer">
        <Button type="text" @click="cancel">取消</Button>
        <Button type="primary" @click="ok">确定</Button>
      </div>
    </Modal>
  </div>
  
</template>
<script>
import {medicineSearch,sportsSearch,foodSearch,foodRecordAdd,medicineRecordAdd,sportsRecordAdd} from '@/api/addPlan';
export default {
  name: 'addModel',
  components:{
  },
  props: {
    show: Boolean,
    addModelData: Object,
    date:String
  },
  data () {
    return {
      visible: this.show,
      time_point_list:[
        {label:'早餐前',value: 1},
        {label:'早餐',value: 2},
        {label:'早餐后',value: 3},
        {label:'午餐前',value: 4},
        {label:'午餐',value: 5},
        {label:'午餐后',value: 6},
        {label:'晚餐前',value: 7},
        {label:'晚餐',value: 8},
        {label:'晚餐后',value: 9},
        {label:'睡前',value: 10},
      ],
      loading:false,
      options:[],
      details:[],
      planId:0,
      historyList:[],
      selectPlaceholder:'',
      queryId:'',
      form: {
        time_point: '',
        time_interval: '',
      }
    }
  },
  watch: {
    show (newv, oldv) {
      this.visible = newv;
      this.init();
    },
    addModelData(newv){
      if(newv.plan){
        this.planId = newv.plan.id;
        this.details = newv.plan.detail;
        this.form.time_point = newv.plan.time_point;
        this.form.time_interval = newv.plan.time_interval
      }
    },
    queryId(newv){
      let that = this;
      if(newv){
        this.options.forEach(item => {
          if(item.id == newv){
            let repect = false;
            this.details.forEach(el =>{
              if(el.id == newv){
                repect = true;
              }
            })
            //去重
            if(!repect){
              this.details.push(item);
              function fixList(name){
                let historyList = Object.assign([],JSON.parse(window.localStorage.getItem(name)))
                if(historyList.length>5){
                  historyList = historyList.slice(-5)
                }
                historyList.push(item)
                window.localStorage.setItem(name,JSON.stringify(historyList));
                that.historyList = historyList;
              }
              //食物
              if(item.food_id){
                fixList('foodListHistory')
              }
              //口服药
              if(item.medicine_id && item.type == 1){
                fixList('medicineListHistory')
              }
              //胰岛素
              if(item.medicine_id && item.type == 2){
                fixList('ydsListHistory')
              }
              //运动
              if(item.sports_id){
                fixList('sportsListHistory')
              }
            }else{
              this.$Message.warning('请勿重复添加');
            }
          }
        })
      }
    }
  },
  mounted () {},
  methods: {
    init(){
      this.queryId = '';
      this.form = {
        time_point: '',
        time_interval: '',
      };
      this.details = [];
      this.options = [];
      this.selectPlaceholder = `请输入${this.addModelData.kind>1?this.addModelData.kind>3?'运动':this.addModelData.kind>2?'胰岛素':'口服药':'食物'}名称`;
      switch(this.addModelData.kind){
        //饮食
        case 1:
          this.historyList = JSON.parse(window.localStorage.getItem('foodListHistory'));
          break;
        //口服药
        case 2:
          this.historyList = JSON.parse(window.localStorage.getItem('medicineListHistory'));
          break;
        //胰岛素
        case 3:
          this.historyList = JSON.parse(window.localStorage.getItem('ydsListHistory'));
          break;
        //运动
        case 4:
          this.historyList = JSON.parse(window.localStorage.getItem('sportsListHistory'));
          break;
      }
    },
    ok () {
      let {time_point} = this.form;
      if(!time_point){
        this.$Message.warning('请选择时间点');
        return
      }
      switch(this.addModelData.kind){
        case 1:
          this.foodRecordAdd()
          break;
        case 2:
          this.medicineRecordAdd(1)
          break;
        case 3:
          this.medicineRecordAdd(2)
          break;
        case 4:
          this.sportsRecordAdd()
          break;   
      }
    },
    cancel () {
      this.$emit('cancel', false)
    },
    search(title){
      if(title){
        this.loading = true
        switch(this.addModelData.kind){
          case 1:
            foodSearch({title}).then(res=>{
              this.loading = false;
              if(res.code == 100000){
                res.data.forEach(item => {
                  item.id = item.food_id;
                  item.num = 0;
                  item.unit_id = item.unit_list[0].id;
                });
                this.options = res.data;
              }
            })
            break;
          case 2:
            medicineSearch({
              title,
              type:1
            }).then(res=>{
              this.loading = false;
              if(res.code == 100000){
                res.data.forEach(item => {
                  item.id = item.medicine_id;
                  item.num = 0;
                  item.unit_id = item.unit_list[0].id;
                });
                this.options = res.data;
              }
            })
            break;
          case 3:
            medicineSearch({
              title,
              type:2
            }).then(res=>{
              this.loading = false;
              if(res.code == 100000){
                res.data.forEach(item => {
                  item.id = item.medicine_id;
                  item.num = 0;
                  item.unit_id = item.unit_list[0].id;
                });
                this.options = res.data;
              }
            })
            break;
          case 4:
            sportsSearch({title}).then(res=>{
              this.loading = false;
              if(res.code == 100000){
                res.data.forEach(item => {
                  item.id = item.sports_id;
                  item.num = 0;
                  item.unit_id = item.unit_list[0].id;
                });
                this.options = res.data;
              }
            })
            break;
        }
      }
    },
    itemDelete(index){
      this.details.splice(index, 1);
    },
    addByHistory(item){
      let flag = true;
      this.details.forEach(el=>{
        if(el.id == item.id){
          this.$Message.warning('请勿重复添加');
          flag = false
          return
        }
      })
      if(flag){
        this.details.push(item);
      }
    },
    foodRecordAdd(){
      let food_record_detail = this.details.map(item=>{
        return {title:item.title,num:item.num,unit_id:item.unit_id,food_id:item.food_id}
      })
      let {user_id} = this.$route.query
      if(food_record_detail.length){
        foodRecordAdd({
          id:this.planId,
          user_id,
          time_point:this.form.time_point,
          source:2,
          food_time:this.date,
          food_record_detail:JSON.stringify(food_record_detail)
        }).then(res=>{
          if(res.code == 100000){
            this.$Message.success(res.msg);
            this.$emit('ok',false)
          }else{
            this.$Message.error(res.msg);
          }
        })
      }
    },
    medicineRecordAdd(type){
      let medicine_record_detail = this.details.map(item=>{
        return {title:item.title,num:item.num,unit_id:item.unit_id,medicine_id:item.medicine_id}
      })
      let {user_id} = this.$route.query
      if(medicine_record_detail.length){
        medicineRecordAdd({
          id:this.planId,
          user_id,
          time_point:this.form.time_point,
          time_interval:this.form.time_interval,
          source:2,
          medicine_time:this.date,
          type,
          medicine_record_detail:JSON.stringify(medicine_record_detail)
        }).then(res=>{
          if(res.code == 100000){
            this.$Message.success(res.msg);
            this.$emit('ok',false)
          }else{
            this.$Message.error(res.msg);
          }
        })
      }
    },
    sportsRecordAdd(){
      let sports_record_detail = this.details.map(item=>{
        return {title:item.title,num:item.num,unit_id:item.unit_id,sports_id:item.sports_id}
      })
      let {user_id} = this.$route.query
      if(sports_record_detail.length){
        sportsRecordAdd({
          id:this.planId,
          user_id,
          time_point:this.form.time_point,
          time_interval:this.form.time_interval,
          source:2,
          sports_time:this.date,
          sports_record_detail:JSON.stringify(sports_record_detail)
        }).then(res=>{
          if(res.code == 100000){
            this.$Message.success(res.msg);
            this.$emit('ok',false)
          }else{
            this.$Message.error(res.msg);
          }
        })
      }
    }
  }
}
</script>
<style lang="less" scoped>
.fromBody{
  .ivu-form-item{
    margin-bottom: 12px;
  }
  .w45{
    width: 45%;
  }
  .details{
    min-height: 150px;
    max-height: 200px;
    overflow-y: scroll;
    .item{
      box-sizing: border-box;
      padding: 0 8px;
      height: 30px;
      background: #F7FBFC;
      border-radius: 4px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      .name{
        font-size: 12px;
        color: #242424;
        max-width: 120px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
      .ipArea{
        display: flex;
        align-items: center;
        justify-content: flex-end;
        .icon{
          font-size: 14px;
          margin-left: 8px;
        }
      }
    }
  }
  .history{
    margin-top: 20px;
    .title{
      font-size: 13px;
      color: #242424;
    }
    .list{
      display: flex;
      flex-wrap: wrap;
      .item{
        cursor: pointer;
        height: 22px;
        padding: 0 8px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #9F9F9F;
        font-size: 12px;
        background-color: #F7FBFC;
        border-radius: 4px;
        margin: 6px 6px 0 0;
        p{
          max-width: 120px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
      }
    }
  }
}
</style>
